package com.yellow.userservice.controller;

import com.yellow.userservice.common.LoginRequestDTO;
import com.yellow.userservice.common.PasswordLoginRequest;
import com.yellow.userservice.common.SMSLoginRequest;
import com.yellow.userservice.entity.User;
import com.yellow.userservice.factory.LoginServiceFactory;
import com.yellow.userservice.service.LoginService;
import com.yellow.userservice.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author: hy
 * @create: 2024-03-23
 */

@Slf4j
@RestController
@Tag(name="登录",description = "登录逻辑")
@CrossOrigin(origins = "*",maxAge =3600 )
public class LoginController {
    @Resource
    private LoginServiceFactory factory;
    @Resource
    private SimpMessagingTemplate messagingTemplate;
    @Resource
    private UserService userService;
    /**
     * Sends a code to the user for login purposes.
     * This method determines the type of login service to use based on the request,
     * and attempts to log the user in with the provided credentials.
     *
     * @param loginRequest The login request containing the login type, identifier, and credential.
     * @return A {@link ResponseEntity} with a success message if login is successful, or a failure message otherwise.
     */
    @PostMapping("/sendCode")
    public ResponseEntity<String> sendCode(@RequestBody LoginRequestDTO loginRequest) {
        LoginService loginService = factory.getLoginService(loginRequest.getType());
        boolean result = loginService.login(loginRequest.getIdentifier(), loginRequest.getCredential());

        if (result) {
            return ResponseEntity.ok("Login successful.");
        } else {
            return ResponseEntity.badRequest().body("Login failed.");
        }
    }

    /**
     * Checks if the provided phone number is associated with a valid user.
     *
     * @param number The phone number to validate.
     * @return true if the phone number is valid and associated with a user, false otherwise.
     */
    @GetMapping("/valid/{number}")
    public boolean isValidPhoneNumber(@PathVariable(value = "number") String number){
        User user = userService.selectByPhoneNumber(number);
        return user!=null;
    }

    /**
     * Handles login requests via SMS.
     * This method assumes that the SMS verification has already been completed on the client side.
     * It retrieves the user associated with the provided phone number and sends a login status message via WebSocket.
     *
     * @param smsLoginRequest The login request containing the phone number.
     * @return A {@link ResponseEntity} containing a success message.
     */
    @PostMapping("/login/sms")
    public ResponseEntity<?> loginWithSMS(@RequestBody SMSLoginRequest smsLoginRequest) {
        // 根据phoneNumber查询到对应的用户
        User user = userService.selectByPhoneNumber(smsLoginRequest.getPhoneNumber());

        // 验证已经在前端处理了，这里发送过来的sms请求必定是通过验证的用户,
        // 发送WebSocket消息的逻辑
        messagingTemplate.convertAndSend("/sms", user);

        return ResponseEntity.ok().body(Map.of("success", true, "message", "登录成功"));
    }

    /**
     * Handles login requests with a username and password.
     * This method verifies the user's credentials and returns user information upon successful authentication.
     *
     * @param loginRequest The login request containing the username and password.
     * @return A {@link ResponseEntity} with user information if authentication is successful, or an error message otherwise.
     */
    @PostMapping("/login/password")
    public ResponseEntity<?> loginWithPassword(@RequestBody PasswordLoginRequest loginRequest) {
        // 根据username查询到对应的用户
        User user = userService.selectByName(loginRequest.getUsername());

        if (user.getPassword().equals(loginRequest.getPassword())) {
            // 密码匹配成功
            //返回成功消息
            Map<String, Object> userInfo = Map.of(
                    "id", user.getUserId(),// 假设有这样一个字段
                    "username", user.getUserName(),
                    "email", user.getUserEmail(),
                    "phoneNumber",user.getPhoneNumber(),
                    "avatarUrl",user.getAvatarUrl(),
                    "password",user.getPassword(),
                    "userType",user.getUserType()
                    // 可以添加更多你需要返回的字段
            );

            // 返回成功消息和用户信息
            return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "登录成功",
                    "user", userInfo
            ));
        } else {
            // 用户名不存在或密码不匹配
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("success", false, "message", "用户名或密码错误"));
        }
    }

}

